/**
 * 物料 - 新建或编辑界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.Goods.GoodsEditForm", {
  extend: "PSI.AFX.Form.EditForm",

  /**
   * 初始化组件
   * 
   * @override
   */
  initComponent() {
    const me = this;
    const entity = me.getEntity();

    me.adding = entity == null;

    const buttons = [];
    if (!entity) {
      buttons.push({
        text: "保存并继续新建",
        ...PSI.Const.BTN_STYLE,
        formBind: true,
        handler() {
          me._onOK(true);
        },
        scope: me
      });
    }

    buttons.push({
      text: "保存",
      ...PSI.Const.BTN_STYLE,
      formBind: true,
      iconCls: "PSI-button-ok",
      handler() {
        me._onOK(false);
      },
      scope: me
    }, {
      text: entity == null ? "关闭" : "取消",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.close();
      },
      scope: me
    });

    let selectedCategory = null;
    let defaultCategoryId = null;

    if (me.getParentForm()) {
      selectedCategory = me.getParentForm().getCategoryGrid()
        .getSelectionModel().getSelection();
      defaultCategoryId = null;
      if (selectedCategory != null && selectedCategory.length > 0) {
        defaultCategoryId = selectedCategory[0].get("id");
      }
    } else {
      // 当 me.getParentForm() == null的时候，本窗体是在其他地方被调用
      // 例如：业务单据中选择物料的界面中，也可以新建物料
    }

    const t = entity == null ? "新建物料" : "编辑物料";
    const logoHtml = me.genLogoHtml(entity, t);

    const width1 = 600;
    const width2 = 295;
    PCL.apply(me, {
      header: {
        title: me.formatTitle(PSI.Const.PROD_NAME),
        height: 40
      },
      width: 650,
      height: 510,
      layout: "border",
      items: [{
        region: "north",
        border: 0,
        height: 70,
        html: logoHtml
      }, {
        region: "center",
        border: 0,
        id: me.buildId(me, "editForm"),
        xtype: "form",
        layout: {
          type: "table",
          columns: 2,
          tableAttrs: PSI.Const.TABLE_LAYOUT,
        },
        height: "100%",
        bodyPadding: 5,
        defaultType: 'textfield',
        fieldDefaults: {
          labelWidth: 70,
          labelAlign: "right",
          labelSeparator: "",
          msgTarget: 'side'
        },
        items: [{
          xtype: "hidden",
          name: "id",
          value: entity == null ? null : entity.get("id")
        }, {
          id: me.buildId(me, "editCategory"),
          xtype: "psi_goodscategoryfield",
          fieldLabel: "分类",
          allowBlank: false,
          blankText: "没有输入物料分类",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          },
          width: width2,
        }, {
          id: me.buildId(me, "editCategoryId"),
          name: "categoryId",
          xtype: "hidden",
          value: defaultCategoryId
        }, {
          id: me.buildId(me, "editCode"),
          fieldLabel: "编码",
          width: width2,
          allowBlank: false,
          blankText: "没有输入物料编码",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          name: "code",
          value: entity == null ? null : entity.get("code"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editName"),
          fieldLabel: "品名",
          colspan: 2,
          width: width1,
          allowBlank: false,
          blankText: "没有输入品名",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          name: "name",
          value: entity == null ? null : entity.get("name"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editSpec"),
          fieldLabel: "规格型号",
          colspan: 2,
          width: width1,
          name: "spec",
          value: entity == null ? null : entity.get("spec"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editUnit"),
          xtype: "psi_goodsunitfield",
          fieldLabel: "计量单位",
          allowBlank: false,
          blankText: "没有输入计量单位",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          name: "unitName",
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          },
          width: width2,
        }, {
          id: me.buildId(me, "editUnitId"),
          xtype: "hidden",
          name: "unitId"
        }, {
          id: me.buildId(me, "editBarCode"),
          fieldLabel: "条形码",
          width: width2,
          name: "barCode",
          value: entity == null ? null : entity.get("barCode"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editBrandId"),
          xtype: "hidden",
          name: "brandId"
        }, {
          id: me.buildId(me, "editBrand"),
          fieldLabel: "品牌",
          name: "brandName",
          xtype: "PSI_goods_brand_field",
          colspan: 2,
          width: width1,
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          fieldLabel: "销售基准价",
          xtype: "numberfield",
          hideTrigger: true,
          name: "salePrice",
          id: me.buildId(me, "editSalePrice"),
          value: entity == null ? null : entity.get("salePrice"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          },
          width: width2,
        }, {
          fieldLabel: "建议采购价",
          xtype: "numberfield",
          width: width2,
          hideTrigger: true,
          name: "purchasePrice",
          id: me.buildId(me, "editPurchasePrice"),
          value: entity == null ? null : entity.get("purchasePrice"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          fieldLabel: "备注",
          name: "memo",
          id: me.buildId(me, "editMemo"),
          value: entity == null ? null : entity.get("memo"),
          listeners: {
            specialkey: {
              fn: me._onLastEditSpecialKey,
              scope: me
            }
          },
          colspan: 2,
          width: width1
        }, {
          id: me.buildId(me, "editRecordStatus"),
          xtype: "combo",
          queryMode: "local",
          editable: false,
          valueField: "id",
          fieldLabel: "状态",
          name: "recordStatus",
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: [[1000, "启用"], [0, "停用"]]
          }),
          value: 1000,
          width: width2,
        }, {
          id: me.buildId(me, "editTaxRate"),
          xtype: "combo",
          queryMode: "local",
          editable: false,
          valueField: "id",
          fieldLabel: "税率",
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: [[-1, "[不设定]"],
            [0, "0%"], [1, "1%"],
            [2, "2%"], [3, "3%"],
            [4, "4%"], [5, "5%"],
            [6, "6%"], [7, "7%"],
            [8, "8%"], [9, "9%"],
            [10, "10%"],
            [11, "11%"],
            [12, "12%"],
            [13, "13%"],
            [14, "14%"],
            [15, "15%"],
            [16, "16%"],
            [17, "17%"]]
          }),
          value: -1,
          name: "taxRate",
          width: width2
        }, {
          id: me.buildId(me, "editMType"),
          xtype: "combo",
          queryMode: "local",
          editable: false,
          valueField: "id",
          fieldLabel: "物料类型",
          name: "mType",
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: [[1000, "原材料"], [2000, "半成品"],
            [3000, "产成品"], [4000, "商品"], [5000, "虚拟件"]]
          }),
          value: 4000,
          width: width2,
        }],
        buttons,
      }],
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
        close: {
          fn: me._onWndClose,
          scope: me
        }
      }
    });

    me.callParent(arguments);

    me.editForm = PCL.getCmp(me.buildId(me, "editForm"));
    me.editCategory = PCL.getCmp(me.buildId(me, "editCategory"));
    me.editCategoryId = PCL.getCmp(me.buildId(me, "editCategoryId"));
    me.editCode = PCL.getCmp(me.buildId(me, "editCode"));
    me.editName = PCL.getCmp(me.buildId(me, "editName"));
    me.editSpec = PCL.getCmp(me.buildId(me, "editSpec"));
    me.editUnit = PCL.getCmp(me.buildId(me, "editUnit"));
    me.editUnitId = PCL.getCmp(me.buildId(me, "editUnitId"));
    me.editBarCode = PCL.getCmp(me.buildId(me, "editBarCode"));
    me.editBrand = PCL.getCmp(me.buildId(me, "editBrand"));
    me.editBrandId = PCL.getCmp(me.buildId(me, "editBrandId"));
    me.editSalePrice = PCL.getCmp(me.buildId(me, "editSalePrice"));
    me.editPurchasePrice = PCL.getCmp(me.buildId(me, "editPurchasePrice"));
    me.editMemo = PCL.getCmp(me.buildId(me, "editMemo"));
    me.editRecordStatus = PCL.getCmp(me.buildId(me, "editRecordStatus"));
    me.editTaxRate = PCL.getCmp(me.buildId(me, "editTaxRate"));
    me.editMType = PCL.getCmp(me.buildId(me, "editMType"));

    // AFX
    me.__editorList = [
      me.editCategory, me.editCode, me.editName,
      me.editSpec, me.editUnit, me.editBarCode, me.editBrand,
      me.editSalePrice, me.editPurchasePrice, me.editMemo
    ];
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.disable();
    }

    // AFX
    PCL.get(window).on('beforeunload', me.__onWindowBeforeUnload);

    me.setFocusAndCursorPosToLast(me.editCode);

    const categoryId = me.editCategoryId.getValue();
    const el = me.getEl();
    el?.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/Goods/goodsInfo"),
      params: {
        id: me.adding ? null : me.getEntity().get("id"),
        categoryId: categoryId
      },
      callback(options, success, response) {
        if (success) {
          const data = me.decodeJSON(response.responseText);

          if (!me.adding) {
            // 编辑商品信息
            me.editCategory.setIdValue(data.categoryId);
            me.editCategory.setValue(data.categoryName);
            me.editCode.setValue(data.code);
            me.editName.setValue(data.name);
            me.editSpec.setValue(data.spec);
            me.editUnit.setIdValue(data.unitId);
            me.editUnit.setValue(data.unitName);
            me.editSalePrice.setValue(data.salePrice);
            me.editPurchasePrice.setValue(data.purchasePrice);
            me.editBarCode.setValue(data.barCode);
            me.editMemo.setValue(data.memo);
            const brandId = data.brandId;
            if (brandId) {
              const editBrand = me.editBrand;
              editBrand.setIdValue(brandId);
              editBrand.setValue(me.htmlDecode(data.brandFullName));
            }
            me.editRecordStatus.setValue(parseInt(data.recordStatus));
            if (data.taxRate) {
              me.editTaxRate.setValue(parseInt(data.taxRate));
            } else {
              me.editTaxRate.setValue(-1);
            }

            if (data.mType) {
              me.editMType.setValue(parseInt(data.mType));
            }
          } else {
            // 新增商品
            if (data.categoryId) {
              me.editCategory.setIdValue(data.categoryId);
              me.editCategory.setValue(data.categoryName);
              const cmt = parseInt(data.categoryMType);
              if (cmt != -1) {
                // cmt == -1表示分类不限物料类型
                me.editMType.setValue(cmt);
              } else {
                me.editMType.setValue(4000);
              }
            } else {
              me.editMType.setValue(4000);
            }
          }
        }

        el?.unmask();
      }
    });
  },

  /**
   * @private
   */
  _onOK(thenAdd) {
    const me = this;

    const categoryId = me.editCategory.getIdValue();
    me.editCategoryId.setValue(categoryId);

    const unitId = me.editUnit.getIdValue();
    me.editUnitId.setValue(unitId);

    const brandId = me.editBrand.getIdValue();
    me.editBrandId.setValue(brandId);

    const f = me.editForm;
    const el = f.getEl();
    el?.mask(PSI.Const.SAVING);
    f.submit({
      url: me.URL("SLN0001/Goods/editGoods"),
      method: "POST",
      success(form, action) {
        el?.unmask();
        me._lastId = action.result.id;
        if (me.getParentForm()) {
          me.getParentForm()._lastId = me._lastId;
        }

        me.tip("数据保存成功", !thenAdd);
        me.focus();

        if (thenAdd) {
          me.clearEdit();
        } else {
          me.close();
          if (me.getParentForm()) {
            me.getParentForm().freshGoodsGrid();
          }
        }
      },
      failure(form, action) {
        el.unmask();
        me.showInfo(action.result.msg, () => {
          me.editCode.focus();
        });
      }
    });
  },

  /**
   * @private
   */
  _onLastEditSpecialKey(field, e) {
    const me = this;

    if (e.getKey() == e.ENTER) {
      const f = me.editForm;
      if (f.getForm().isValid()) {
        me._onOK(me.adding);
      }
    }
  },

  /**
   * @private
   */
  clearEdit() {
    const me = this;

    me.editCode.focus();

    const editors = [
      me.editCode, me.editName, me.editSpec, me.editSalePrice,
      me.editPurchasePrice, me.editBarCode, me.editMemo
    ];
    for (let i = 0; i < editors.length; i++) {
      const edit = editors[i];
      edit.setValue(null);
      edit.clearInvalid();
    }
  },

  /**
   * @private
   */
  _onWndClose() {
    const me = this;

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.enable();
    }

    // AFX
    PCL.get(window).un('beforeunload', me.__onWindowBeforeUnload);

    if (me.getParentForm()) {
      me.getParentForm()._lastId = me._lastId;
      me.getParentForm().freshGoodsGrid();
    }
  }
});
